<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-if="false" v-model="listQuery.lineId" :placeholder="$t('equipment.lineNumber')" class="filter-item" style="width: 200px" @change="handleLineSelect">
        <el-option v-for="item in lineOptions" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
      </el-select>
      <el-select v-model="listQuery.processNumber" :placeholder="$t('equipment.processNumber')" class="filter-item" clearable="" style="width: 350px" @change="handleFilter">
        <el-option v-for="process in processOptions" :key="process.processNumber" :label="process.processName+'_'+process.processNumber" :value="process.processNumber" />
      </el-select>
      <el-date-picker v-model="listQuery.startTime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.startDate')" class="filter-item" />
      <el-date-picker v-model="listQuery.endTime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.endDate')" class="filter-item" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <div class="table-container">
      <div class="components-container-board">
        <!--所有结果-->
        <el-table
          ref="dragTable"
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          :header-row-style="{color: 'black'}"
          :header-cell-style="{background: 'lightBlue'}"
          border
          fit
          row-key="id"
          highlight-current-row
          :row-style="{height:'20px'}"
          :cell-style="{padding:'2px'}"
        >
          <el-table-column :label="$t('tracibility.productId')" width="220px" align="center">
            <template slot-scope="{row}">
              <span class="link-type" @click="handleCheckProcess(row)">{{ row.productId }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('produce.typeNo')" width="auto" align="center">
            <template slot-scope="{row}">
              <span>{{ row.typeNo }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('tracibility.testTime')" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" sortable="custom" prop="creatTime" width="200px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.testTime }}</span>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" :label="$t('tracibility.processStatus')" width="180">
            <template slot-scope="{row}">
              <el-tag :type="row.processStatus==='OK'? 'success':'danger'">
                {{ row.processStatus }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
        <!--所选择的结果-->
        <h3>{{ $t('rework.sample') }}</h3>
        <el-collapse v-for="(process,index) in processList" :key="process.uniqueId">
          <el-collapse-item>
            <template slot="title">
              <div style="width:100%; ">
                <span style="margin-left: 20px;">{{ index }}</span>
                <el-tag style="margin-left: 20px;" class="resultSpan" :type="process.processStatus==='OK'? 'success':'danger'">
                  {{ process.processStatus }}
                </el-tag>
                <el-tag style="margin-left: 20px;" class="resultSpan" :type="process.processStatus==='OK'? 'success':'danger'">
                  {{ process.testTime }}
                </el-tag>
                <el-tag style="margin-left: 20px;" :type="process.processStatus==='OK'? 'success':'danger'">
                  {{ $t('tracibility.productId') + ': '+ process.productId }}
                </el-tag>
                <div style="float: right">
                  <span @click="handleDelete(process,index)">
                    <i style="color:#ff4949; width:30px; height:30px; margin-right:30px" class="el-icon-delete" />
                  </span>
                </div>
              </div>
            </template>
            <template>
              <el-table
                :key="tableKey"
                v-loading="listLoading"
                :data="process.processResults"
                :header-row-style="{color: 'black'}"
                :header-cell-style="{background: 'lightBlue'}"
                border
                fit
                highlight-current-row
                :row-style="{height:'20px'}"
                :cell-style="{padding:'2px'}"
                style="padding: 0px,width: 100%;"
              >
                <el-table-column :label="$t('equipment.resultCode')" width="150px" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.resultCode }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('equipment.resultName')" width="200px" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.resultName }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('tracibility.resultValue')" width="150px" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.resultValue }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('tracibility.unit')" width="100px" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.unit }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('tracibility.minValue')" width="150px" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.minValue }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('tracibility.standardValue')" width="150px" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.standardValue }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('tracibility.maxValue')" width="150px" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.maxValue }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('tracibility.resultStatus')" width="100px" align="center">
                  <template slot-scope="{row}">
                    <el-tag :type="row.resultStatus==='OK'? 'success':'danger'">
                      {{ row.resultStatus }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div class="select-board">
        <Sticky style="margin-left:50px;">
          <h4 align="center" style="padding:0">{{ $t('rework.cpkList') }}</h4>
          <div v-for="(element,index) in processResults" :key="element.resultCode" :style="{background: handleIndex == index? 'lightblue':'lightgray'}" class="list-complete-item">
            <div class="list-complete-item-handle" @click="handleSetRange(element,index)">
              {{ element.resultName }}[{{ element.resultCode }}]
            </div>
          </div>
        </Sticky>
      </div>
    </div>
    <!-- 新建和更新对话框 -->
    <el-dialog v-el-drag-dialog width="1050px" :visible.sync="dialogFormVisible">
      <cpk-form :cpk-data="cpkData" />
    </el-dialog>
    <!-- 新建和更新对话框 -->
    <el-dialog v-el-drag-dialog :visible.sync="dialogFormVisible2">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('equipment.resultCode')" required>
          <el-input v-model="temp.resultCode" :readonly="true" />
        </el-form-item>
        <el-form-item :label="$t('equipment.resultName')" required>
          <el-input v-model="temp.resultName" :readonly="true" />
        </el-form-item>
        <el-form-item :label="$t('tracibility.minValue')" required prop="minValue">
          <el-input v-model="temp.minValue" clearable="" />
        </el-form-item>
        <el-form-item :label="$t('tracibility.standardValue')" required prop="standardValue">
          <el-input v-model="temp.standardValue" clearable />
        </el-form-item>
        <el-form-item :label="$t('tracibility.maxValue')" required prop="maxValue">
          <el-input v-model="temp.maxValue" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleGetCpk()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLineList, getProcessList, getProcessResultList } from '@/api/equipment'
import { getProcessList2 } from '@/api/tracibility'
import { CaculateCpk } from '@/api/rework'
import CpkForm from './components/cpkForm.vue'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'
import Sticky from '@/components/Sticky'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ProcessResultDef',
  components: {
    Sticky,
    CpkForm,
    Pagination
  },
  directives: { waves, elDragDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      tableKey: 0,
      processResults: [{ resultCode: 'S010_001', resultName: '电压' }],
      handleIndex: 0,
      list: [],
      processList: [],
      newList: [],
      cpkData: {},
      sortable: null,
      lineOptions: [],
      processOptions: [],
      // 任务u状态
      stateOptions: [{ label: '所有', key: 0, color: 'white' },
        { label: '进行中', key: 1, color: 'green' },
        { label: '延期', key: 2, color: 'orange' },
        { label: '完成', key: 3, color: 'darkblue' },
        { label: '取消', key: 4, color: 'red' },
        { label: '暂停', key: 5, color: 'yellow' }],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineId: this.$store.getters.lineId,
        lineName: '',
        lineNumber: this.$store.getters.lineNumber,
        processNumber: '',
        resultCode: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+processNumber'
      },
      showReviewer: false,
      showRemark: false,
      temp: {
        resultCode: '',
        resultName: '',
        minValue: 0,
        standardValue: 0,
        maxValue: 0
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        minValue: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        standardValue: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        maxValue: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        director: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        director: false
      }
    }
  },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    // this.getLineOptions()
    this.getProcessOptions()
    this.getList()
  },
  methods: {
    timestepToolTip(index) {
      return index + '%'
    },
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取线体清单
    getLineOptions() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        if (this.lineOptions.length > 0) {
          this.listQuery.lineId = this.lineOptions[0].lineId
        }
        this.listLoading = false
      })
    },
    // 获取工艺流程选项
    getProcessOptions() {
      this.listLoading = true
      this.processOptions = []
      getProcessList(this.listQuery).then(response => {
        this.processOptions = response.data.processes
        this.listLoading = false
      })
    },
    // 判断线体ID是否为空
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineId === undefined || this.listQuery.lineId === 0)
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.warn'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'warn',
          duration: 2000
        })
      }
      return ret
    },
    // 判断工艺好是否为空
    isEmptyProcessNumberId: function() {
      var ret = (this.listQuery.processNumber === undefined || this.listQuery.processNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.warn'),
          message: i18n.t('msg.NO_PROCESSING_SELECTED'),
          type: 'warn',
          duration: 2000
        })
      }
      return ret
    },
    // 获取清单
    getList() {
      if (this.isEmptyLineId() === false && this.isEmptyProcessNumberId() === false) {
        this.listLoading = true
        getProcessList2(this.listQuery).then(response => {
          this.list = response.data.processes
          this.total = response.data.total
          this.processList.forEach(l => {
            var idx = 0
            for (idx = 0; idx < this.list.length; idx++) {
              if (this.list[idx].uniqueId === l.uniqueId) {
                break
              }
            }
            this.list.splice(idx, 1)
          })
          this.listLoading = false
        })
        getProcessResultList(this.listQuery).then(response => {
          this.processResults = response.data.processResults
          this.listLoading = false
        })
      }
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.processList = []
      this.getList()
    },
    // 设置范围
    handleSetRange(element, index) {
      this.temp.resultCode = element.resultCode
      this.temp.resultName = element.resultName
      this.dialogFormVisible2 = true
    },
    // 显示Cpk报告
    handleGetCpk() {
      var value = []
      for (var idx = 0; idx < this.processList.length; idx++) {
        this.processList[idx].processResults.forEach(el => {
          if (this.temp.resultCode === el.resultCode) {
            value.push(parseFloat(el.resultValue))
            return
          }
        })
      }
      console.log(this.processList, value, this.temp.resultCode)
      var group = Math.floor(value.length / 5)
      if (group >= 1) {
        value.splice(group * 5, value.length)
        CaculateCpk({ values: value, minValue: this.temp.minValue,
          maxValue: this.temp.maxValue, standardValue: this.temp.standardValue }).then(response => {
          this.cpkData = { values: value, range: this.temp, data: response.data }
          this.dialogFormVisible2 = false
          this.dialogFormVisible = true
        })
      }
    },
    // 初始化创建信息
    resetTemp() {
      this.temp.processResultId = 0
      this.temp.processId = this.processOptions.length > 0 ? this.processOptions[0].processId : ''
      this.processOptions.forEach(e => {
        if (e.processNumber === this.listQuery.processNumber) {
          this.temp.processId = e.processId
          return
        }
      })
      this.temp.resultCode = ''
      this.temp.resultName = ''
      this.temp.resultUnit = ''
      this.temp.processName = ''
    },
    handleLineSelect() {
      this.listQuery.processNumber = ''
      this.processOptions = []
      this.List = []
      this.processResults = []
      getProcessList(this.listQuery).then(response => {
        this.processOptions = response.data.processes
      })
    },
    // 选择数据
    handleCheckProcess(row) {
      const ret = Object.assign({}, row) // copy obj
      this.processList.push(ret)
      const index = this.list.findIndex(v => v.uniqueId === ret.uniqueId)
      this.list.splice(index, 1)
    },
    // 删除数据库信息
    handleDelete(row, index) {
      const item = Object.assign({}, row) // copy obj
      this.list.push(item)
      this.processList.splice(index, 1)
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('equipment.resultCode'),
          i18n.t('equipment.resultName'),
          i18n.t('equipment.resultUnit'),
          i18n.t('equipment.processName')]
        const filterVal = ['resultCode', 'resultName', 'resultUnit', 'processName']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '工艺结果定义' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss">
.app-container {
  padding: 32px;
  bottom: 20px;
  background-color: white;
  position: relative;
  .table-container {
    width:100%;
    top:10px;
    bottom: 20px;
    position:relative;
      .components-container-board {
        width: 75%;
        float:left;
      }
      .select-board {
        width: 20%;
        height: 100%;
        font-size: 16px;
        align-content: center;
        float: right;
      }
    }
  .list-complete-item {
  cursor: pointer;
  position: relative;
  font-size: 14px;
  padding: 5px 12px;
  margin-top: 4px;
  border: 1px solid #bfcbd9;
  transition: all 1s;
}
.list-complete-item-handle {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
}
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
